{% extends "main.tpl" %}
{% block stylesheets %}
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/form.css?v=1">
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/switches.css?v=1">
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/agenda.css?v=1">
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/dashboard.css?v=1">
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/modal.css?v=1">
	<link rel="stylesheet" href="{{ stylesheet_path }}styles/progress-slider.css?v=1">
    
	<!-- glDatePicker -->
	<link rel="stylesheet" href="js/libs/glDatePicker/developr.css?v=1">

	<!-- jQuery Form Validation -->
	<link rel="stylesheet" href="js/libs/formValidator/developr.validationEngine.css?v=1">
{% endblock %}
{% block content_title %}Dashboard{% endblock %}
{% block content %}
<button id="authorize-button" style="visibility: hidden">Authorize</button>

		<div class="with-padding">
			<div class="columns">
                <div class="four-columns twelve-columns-tablet">
                    <div class="block">
                        <h3 class="block-title">Statistics</h3>
                        <div class="with-padding">
                            <p>Between {{ analytics.start_date }} and {{ analytics.end_date }}</p>
                            <ul class="stats">
                            
                                <!-- With link -->
                                <li>
                                    <strong id="unique_visits">-</strong> Unique <br>Visits
                                </li>
                            
                                <!-- Without link -->
                                <li>
                                    <strong id="new_visits">-</strong> New <br>Visits
                                </li>
                                <li>
                                    <strong id="total_pageviews">-</strong> Total<br />Pageviews
                                </li>
                                <li>
                                    <strong id="visit_duration">-</strong> Avarage<br />Visit duration
                                </li>
                                <li>
                                    <strong id="bounce_rate">-</strong> Bounce <br>Rate
                                </li>
                                <li>
                                    <strong id="new_visits_percent">-</strong>  % <br>New Visits
                                </li>
                            
                            </ul>            
                    
                        </div>
                    </div>
                
                
                
                </div>
            </div>
		</div>

<div id="output">Results:<br></div>	
{% endblock %}

{% block javascripts %}






	<script src="{{ javascript_path }}developr.input.js"></script>
	<script src="{{ javascript_path }}developr.message.js"></script>
	<script src="{{ javascript_path }}developr.modal.js"></script>
	<script src="{{ javascript_path }}developr.navigable.js"></script>
	<script src="{{ javascript_path }}developr.notify.js"></script>
	<script src="{{ javascript_path }}developr.scroll.js"></script>
	<script src="{{ javascript_path }}developr.progress-slider.js"></script>
	<script src="{{ javascript_path }}developr.tooltip.js"></script>
	<script src="{{ javascript_path }}developr.confirm.js"></script>
	<script src="{{ javascript_path }}developr.agenda.js"></script>
	<script src="{{ javascript_path }}developr.tabs.js"></script>		<!-- Must be loaded last -->

	<!-- glDatePicker -->
	<script src="{{ javascript_path }}libs/glDatePicker/glDatePicker.min.js?v=1"></script>

	<!-- jQuery Form Validation -->
	<script src="{{ javascript_path }}libs/formValidator/jquery.validationEngine.js?v=1"></script>
	<script src="{{ javascript_path }}libs/formValidator/languages/jquery.validationEngine-en.js?v=1"></script>

	<!-- Tinycon -->
	<script src="{{ javascript_path }}libs/tinycon.min.js"></script>

	<script>

		// Call template init (optional, but faster if called manually)
		$.template.init();

  </script>



<script src="{{ javascript_path }}libs/jquery-1.7.2.min.js"></script>
<script>
var clientId = '{{ config_item("analytics_client_id") }}';
var apiKey = '{{ config_item("analytics_api_key") }}';
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';
var tableId = 'ga:{{ config_item("analytics_profile") }}';

/**
 * Callback executed once the Google APIs Javascript client library has loaded.
 * The function name is specified in the onload query parameter of URL to load
 * this library. After 1 millisecond, checkAuth is called.
 */
function handleClientLoad() {
  gapi.client.setApiKey(apiKey);
  window.setTimeout(checkAuth, 1);
}


/**
 * Uses the OAuth2.0 clientId to query the Google Accounts service
 * to see if the user has authorized. Once complete, handleAuthResults is
 * called.
 */
function addResult(name, value)
{
 var title = $(document.createElement('span'));
 var content = $(document.createElement('span'));
 title.html(name + " = ");
 content.html(value +"<br>");
 $('#output').append(title).append(content);
}
function getChartObj() {
  var params_ = {
    'chs': '', // Image Dimensions
    'chtt': '', // Title
    'chxt': '', // Axes
    'chts': '', // Title Style
    'cht': '', // Chart type
    'chd': '', // Data
    'chdl': '', // Legend
    'chco': '', // Colors
    'chbh': '', // Width and spacing
    'chxl': '', // Axis Labels
    'chds': '', // Scaling
    'chxr': '', // Axis Scaling
    'chm': ''   // Chart Markers
  };
  var baseURL_ = 'https://chart.googleapis.com/chart';

  function getParams_() {
    return params_;
  }

  function getParam_(key) {
    return params_[key];
  }

  function setParam_(key, val) {
    if (params_[key] !== undefined) {
      params_[key] = val;
    }
  }

  function setParams_(obj) {
    for (key in obj) {
      setParam_(key, obj[key]);
    }
  }

  /**
   * Given a base URL and an array of parameters, construct the complete URL.
   * @return {string} The complete URL for the chart.
  */
  function getURL_() {
    paramArray = [];
    for (key in params_) {
      if (params_[key]) {
        pairStr = [key, params_[key]].join('=');
        paramArray.push(pairStr);
      }
    }
    paramStr = paramArray.join('&');
    url = [baseURL_, paramStr].join('?');
    return url;
  }

  return {
    'getParam': getParam_,
    'getParams': getParams_,
    'setParam': setParam_,
    'setParams': setParams_,
    'getURL': getURL_
  };
}

function getBarChart(chartData) {

  var chart = getChartObj();
  var returningVisitorsStr = chartData.returningVisitors.join();
  var newVisitorsStr = chartData.newVisitors.join();
  var maxValue = chartData.maxReturningVisitors + chartData.maxNewVisitors;

  scaleData = getScaleData(maxValue);

  // Set chart meta-data
  chart.setParams({
    'chs': '500x150', //Image dimensions
    'chxt': 'x,y', //Axes
    'chts': '000000,15', //Title Style
    'cht': 'bvs', //Chart Type (Bar, Vertical, Stacked)
    'chco': 'a3d5f7,389ced', //Colors
    'chbh': 'a,5,20', //Width & Spacing
    'chm': 'N,FF0000,-1,,12', //Markers
    'chtt': 'Visitors+By+Type', //Title
    'chdl': 'Returning+Visitors|New+Visitors', //Legend
    'chd': 't:' + returningVisitorsStr + '|' + newVisitorsStr, //Chart Data
    'chxl': '0:|' + chartData.days.join('|'), //Axis Labels
    'chds': '0,' + scaleData[0], //Scaling
    'chxr': '1,0,' + scaleData[0] + ',' + scaleData[1] //Axis Scaling
  });

  return chart;
}


function checkAuth() {
  gapi.auth.authorize({
    client_id: clientId, scope: scopes, immediate: true}, function(authResult){
		// Auth complete
	  if (authResult) {
		gapi.client.load('analytics', 'v3', function(){
		  var authorizeButton = document.getElementById('authorize-button');
		  authorizeButton.style.visibility = 'hidden';
		  
		    gapi.client.analytics.data.ga.get({
			'ids': tableId,
			'start-date': '{{ analytics.start_date }}',
			'end-date': '{{ analytics.end_date }}',
			'metrics': 'ga:visits',
			'dimensions': 'ga:day,ga:visitorType',
			'sort': '-ga:day',
			//'filters': 'ga:medium==organic',
			'max-results': 25
		  }).execute(function(results){
			  console.log(results)
			  function getVisitorChartData(result) {
				  var entries = result.feed.getEntries();
				  var returningVisitors = [];
				  var newVisitors = [];
				  var days = [];
				  var maxReturningVisitors = 0;
				  var maxNewVisitors = 0;
				
				  for (var i = 0, entry; entry = entries[i]; ++i) {
					var visType = entry.getValueOf('ga:visitorType');
					var numVisits = entry.getValueOf('ga:visits');
					var day = parseInt(entry.getValueOf('ga:day'), 10);
				
					// At the beginning of each day, check if data was missing for previous
					// day.  Insert "0" in appropriate visitor's array as necessary, using
					// fillToSameSize helper method.
					if (!days.length) {
					  days.push(day);
					} else {
					  var lastDay = days[days.length - 1];
					  if (day != lastDay) {
						days.push(day);
						fillToSameSize(newVisitors, returningVisitors);
					  }
					}
				
					if (visType == 'New Visitor') {
					  newVisitors.push(numVisits);
					  maxNewVisitors = Math.max(maxNewVisitors, numVisits);
					} else {
					  returningVisitors.push(numVisits);
					  maxReturningVisitors = Math.max(maxReturningVisitors, numVisits);
					}
				  }
				  fillToSameSize(newVisitors, returningVisitors);
				
				  return {
					'returningVisitors': returningVisitors,
					'newVisitors': newVisitors,
					'maxNewVisitors': maxNewVisitors,
					'maxReturningVisitors': maxReturningVisitors,
					'days': days
				  };							
		    }
			function fillToSameSize(firstArray, secondArray) {
				 if (firstArray.length < secondArray.length) {
					firstArray.push(fillValue);
				  } else if (secondArray.length < firstArray.length) {
					secondArray.push(fillValue);
				  }
			}
			
			var groupedChart = getChartObj();
			var barChart = getBarChart(getVisitorChartData(results));
groupedChart.setParams(barChart.getParams());
groupedChart.setParam('cht', 'bvg');
groupedChart.setParam('chm', 'N,FF0000,0,,12|N,FF0000,1,,12');
var groupedChartURL = groupedChart.getURL();
drawChart('visitorDiv',groupedChartURL);
		  });
		  
		   // statistics
		    gapi.client.analytics.data.ga.get({
			'ids': tableId,
			'start-date': '{{ analytics.start_date }}',
			'end-date': '{{ analytics.end_date }}',
			'metrics': 'ga:visits,ga:newVisits,ga:percentNewVisits,ga:avgTimeOnSite,ga:visitBounceRate,ga:pageviews',
			'dimensions': 'ga:source,ga:keyword',
			'sort': '-ga:visits,ga:source',
			'filters': 'ga:medium==organic',
			'max-results': 25
		  }).execute(function(results){
			  if (!results.code) {
				//alert(results);
				console.log(results)

				  var totals = results.totalsForAllResults;
				
				  for (metricName in totals) {
					  addResult(metricName, totals[metricName]);
				
						$('#unique_visits').html(totals['ga:visits']);
						$('#new_visits').html(totals['ga:newVisits']);
						$('#new_visits_percent').html(Math.floor(totals['ga:percentNewVisits']));
						$('#bounce_rate').html(Math.floor(totals['ga:visitBounceRate']));
						$('#total_pageviews').html(totals['ga:pageviews']);
						$('#unique_visits').html(totals['ga:visits']);
						
						//addResult(metricName, totals[metricName]);
					
				  }			
			  } else {
				alert('There was an error: ' + results.message);
			  }		  
			  
		  });			
			
		});
	  } else {
		  var authorizeButton = document.getElementById('authorize-button');
		
		  authorizeButton.style.visibility = '';
		  authorizeButton.onclick = handleAuthClick;
		  outputToPage('Please authorize this script to access Google Analytics.');
	  }	
	});
}


/**
 * Handler that is called once the script has checked to see if the user has
 * authorized access to their Google Analytics data. If the user has authorized
 * access, the analytics api library is loaded and the handleAuthorized
 * function is executed. If the user has not authorized access to their data,
 * the handleUnauthorized function is executed.
 * @param {Object} authResult The result object returned form the authorization
 *     service that determine whether the user has currently authorized access
 *     to their data. If it exists, the user has authorized access.
 */
function handleAuthResult(authResult) {
  if (authResult) {
    gapi.client.load('analytics', 'v3', handleAuthorized);
  } else {
    handleUnauthorized();
  }
}


/**
 * Updates the UI once the user has authorized this script to access their
 * data. This changes the visibiilty on some buttons and adds the
 * makeApiCall click handler to the run-demo-button.
 */
function handleAuthorized() {
  var authorizeButton = document.getElementById('authorize-button');
  var runDemoButton = document.getElementById('run-demo-button');

  authorizeButton.style.visibility = 'hidden';
  runDemoButton.style.visibility = '';
  runDemoButton.onclick = makeApiCall;
  outputToPage('Click the Run Demo button to begin.');
}


/**
 * Updates the UI if a user has not yet authorized this script to access
 * their Google Analytics data. This function changes the visibility of
 * some elements on the screen. It also adds the handleAuthClick
 * click handler to the authorize-button.
 */
function handleUnauthorized() {
  var authorizeButton = document.getElementById('authorize-button');
  var runDemoButton = document.getElementById('run-demo-button');

  runDemoButton.style.visibility = 'hidden';
  authorizeButton.style.visibility = '';
  authorizeButton.onclick = handleAuthClick;
  outputToPage('Please authorize this script to access Google Analytics.');
}


/**
 * Handler for clicks on the authorization button. This uses the OAuth2.0
 * clientId to query the Google Accounts service to see if the user has
 * authorized. Once complete, handleAuthResults is called.
 * @param {Object} event The onclick event.
 */
function handleAuthClick(event) {
  gapi.auth.authorize({
    client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
  return false;
}

</script>
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
    
{% endblock %}